<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/11/27
 * Time: 11:26
 */

namespace App\HttpController;


use EasySwoole\Component\Di;
use EasySwoole\Http\AbstractInterface\AbstractRouter;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use FastRoute\RouteCollector;

class Router extends AbstractRouter
{

    private $routeCollector;
    /**
     * 初始化路由
     * @param RouteCollector $routeCollector
     * @throws \ReflectionException
     */
    function initialize(RouteCollector $routeCollector)
    {
        // 开启全局拦截
        $this->setGlobalMode(true);

        // 将路由控制器对象放入属性
        $this->routeCollector = $routeCollector;

        // 引入Route文件夹下的所有路由文件
        $this->scanRouter();

        // 注册异常处理
        // |-- 未找到处理方法
        $this->setMethodNotAllowCallBack(function (Request $request,Response $response){
            $response->write('未找到处理方法');
            return false;
        });
        // |-- 未找到路由匹配
        $this->setRouterNotFoundCallBack(function (Request $request,Response $response){
            $response->write('未找到路由匹配');
            return false;
        });

    }

    /**
     * 包含route文件夹下的所有文件
     * @param string $path
     * @throws \ReflectionException
     */
    private function scanRouter(string $path = '')
    {
        $base_path = EASYSWOOLE_ROOT . '/App/Router';
        $path = $path ? $path : $base_path;
        $temp = scandir($path);
        //遍历文件夹
        foreach($temp as $v){
            $a = $path . '/' . $v;
            if(is_dir($a)){//如果是文件夹则执行
                if($v == '..' || $v == '.') continue;
                $this->scanRouter($a);
            }else{
                // 根据文件名组装类名
                $namespace = str_replace('/','\\',str_replace($base_path, 'App\Router',$path));
                $class_name = str_replace('.php','', $v);
                $class = $namespace.'\\'.$class_name;
                // 反射执行index方法
                (new \ReflectionMethod($class, 'index'))->invoke(new $class(),$this->routeCollector);
            }
        }
    }
}